package vip.aster.workflow.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.aster.common.utils.PageInfo;
import vip.aster.workflow.entity.WfApp;
import vip.aster.workflow.mapper.WfAppMapper;
import vip.aster.workflow.query.WfAppQuery;
import vip.aster.workflow.service.WfAppService;
import vip.aster.workflow.vo.WfAppVO;

import java.util.List;

/**
 * <p>
 * 应用管理 服务实现类
 * </P>
 *
 * @author Aster lipian1004@163.com
 * @since 2024-05-11 09:48:46
 */
@Service
@AllArgsConstructor
public class WfAppServiceImpl extends ServiceImpl<WfAppMapper, WfApp> implements WfAppService {

    /**
     * 应用管理Mapper
     */
    private WfAppMapper wfAppMapper;

    @Override
    public PageInfo<WfAppVO> pageList(WfAppQuery query) {
        Page<WfApp> page = new Page<>(query.getPageNum(), query.getPageSize());
        LambdaQueryWrapper<WfApp> wrapper = getWrapper(query);
        wrapper.orderByAsc(WfApp::getSort);
        Page<WfApp> pageList = wfAppMapper.selectPage(page, wrapper);
        return new PageInfo<>(WfAppVO.convertList(pageList.getRecords()), pageList.getTotal());
    }

    /**
     * 查询应用集合
     *
     * @param query 查询条件
     * @return 查询结果
     */
    @Override
    public List<WfAppVO> list(WfAppQuery query) {
        LambdaQueryWrapper<WfApp> wrapper = getWrapper(query);
        wrapper.orderByAsc(WfApp::getSort);
        return WfAppVO.convertList(wfAppMapper.selectList(wrapper));
    }

    @Override
    public void save(WfAppVO vo) {
        WfApp entity = vo.reconvert();
        if (StrUtil.isNotBlank(entity.getId())) {
            wfAppMapper.updateById(entity);
        } else {
            wfAppMapper.insert(entity);
        }
    }

    private LambdaQueryWrapper<WfApp> getWrapper(WfAppQuery query) {
        LambdaQueryWrapper<WfApp> wrapper = Wrappers.lambdaQuery();
        if (query != null) {
            wrapper.like(StringUtils.isNotBlank(query.getName()), WfApp::getName, query.getName());
            wrapper.eq(StringUtils.isNotBlank(query.getStatus()), WfApp::getStatus, query.getStatus());
        }
        return wrapper;
    }

}
